package com.kly.cashmall.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

import java.util.Locale;

/**
 * @author zxp
 * @since 27/10/21
 */
public class NetStateUtil {
    public static final int WIFI = 1;
    public static final int MOBILE = 2;
    public static final int NONE = -1;

    public NetStateUtil() {
    }

    public static int getConnectState(Context context) {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService("connectivity");
        if (manager == null) {
            return -1;
        } else {
            NetworkInfo netWorkInfo = manager.getActiveNetworkInfo();
            if (netWorkInfo != null && netWorkInfo.isAvailable() && netWorkInfo.isConnected()) {
                return netWorkInfo.getType() == 1 ? 1 : 2;
            } else {
                return -1;
            }
        }
    }

    public static String getConnectedType(Context context) {
        String type = "unknown";
        if (getConnectState(context) == 1) {
            type = "wifi";
        } else if (getConnectState(context) == 2) {
            type = "mobile";
        }

        return type;
    }

    public static boolean isConnected(Context context) {
        return getConnectState(context) != -1;
    }

    public static String getWifiIPV4Address(Context context) {
        WifiManager wm = (WifiManager)context.getSystemService("wifi");
        String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
        return ip;
    }

    public static String getWifiIP(Context context) {
        try {
            WifiManager wifiManager = (WifiManager)context.getSystemService("wifi");
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            return String.format(Locale.getDefault(), "%d.%d.%d.%d", ipAddress & 255, ipAddress >> 8 & 255, ipAddress >> 16 & 255, ipAddress >> 24 & 255);
        } catch (Exception var4) {
            var4.printStackTrace();
            return "";
        }
    }
}
